package com.wwg.geoquiz

import android.app.ActivityOptions
import android.app.ComponentCaller
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import android.graphics.PorterDuff
import android.os.Build
import android.view.Gravity
import androidx.lifecycle.ViewModelProvider
import com.wwg.geoquiz.model.Choose
import com.wwg.geoquiz.model.QuizViewModel

private const val KEY_INDEX = "index"
private const val EXTRA_Result = "result"

class MainActivity : ComponentActivity() {

    private val TAG = "MainActivity"
    private lateinit var textView: TextView
    private lateinit var trueButton: Button
    private lateinit var nextButton: Button
    private lateinit var falseButton: Button
    private lateinit var lastutton: Button
    private lateinit var cheatButton: Button

    // 惰性初始化quizViewModel
    private val quizViewModel: QuizViewModel by lazy {
        ViewModelProvider(this).get(QuizViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        Log.d(TAG, "onCreate(Bundle?) called")
        super.onCreate(savedInstanceState)
        showCustomToast("欢迎来到地理知识问答！")
        setContentView(R.layout.main_activity)
        val currentIndex = savedInstanceState?.getInt(KEY_INDEX, 0) ?: 0
        quizViewModel.currentNum = currentIndex

        trueButton = findViewById(R.id.true_button)
        textView = findViewById(R.id.main_text)
        trueButton = findViewById(R.id.true_button)
        falseButton = findViewById(R.id.false_button)
        textView.setText(quizViewModel.questionText)
        nextButton = findViewById(R.id.next_button)
        lastutton = findViewById(R.id.last_button)
        cheatButton = findViewById(R.id.cheat_button)

        updateQuestion(null)

        trueButton.setOnClickListener {
            if (quizViewModel.currentQuestion.cheating == true) {
                Toast.makeText(this, "cheating！！！！！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (quizViewModel.currentQuestion.flag == 0) {
                var answer = judgeAnswer(true, trueButton)
                updateColor(answer, trueButton, falseButton)
                quizViewModel.chooseList.set(quizViewModel.currentNum, Choose(true, answer, false))
            }
        }
        falseButton.setOnClickListener {
            if (quizViewModel.currentQuestion.cheating == true) {
                Toast.makeText(this, "cheating！！！！！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (quizViewModel.currentQuestion.flag == 0) {
                var answer = judgeAnswer(false, falseButton)
                updateColor(answer, falseButton, trueButton)
                quizViewModel.chooseList.set(quizViewModel.currentNum, Choose(false, answer, true))
            }
        }

        nextButton.setOnClickListener {
            trueButton.background.colorFilter = null
            falseButton.background.colorFilter = null
            updateQuestion(true)
        }
        lastutton.setOnClickListener {
            trueButton.background.colorFilter = null
            falseButton.background.colorFilter = null
            updateQuestion(false)
        }
        cheatButton.setOnClickListener {view ->
//            val intent = Intent(this, CheatActivity::class.java)
            val answer = quizViewModel.currentQuestionAnswer
            val intent: Intent = CheatActivity.newIntent(this, answer)
            val options = ActivityOptions
                .makeClipRevealAnimation(view, 0, 0, view.width, view.height)
            startActivityForResult(intent, 100,options.toBundle())
//            startActivity(intent)
        }
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?,
        caller: ComponentCaller
    ) {
        super.onActivityResult(requestCode, resultCode, data, caller)
        if (requestCode == 100) {
            if (resultCode == 101) {
                var b: Boolean = data?.getBooleanExtra(EXTRA_Result, false) == true
                quizViewModel.cheating(b)
//                Log.d("wwg1111111","wwg"+b)
            }
        }
    }

    fun judgeAnswer(answer: Boolean, button: Button): Boolean {
        if (answer == quizViewModel.currentQuestion.key) {
            Toast.makeText(this, R.string.answer_right, Toast.LENGTH_SHORT).show()
            quizViewModel.score += 1
            return true;
        } else
            Toast.makeText(this, R.string.answer_wrong, Toast.LENGTH_SHORT).show()
        return false
    }

    fun chooseButton(k: Boolean): Button {
        if (k == true)
            return trueButton
        else
            return falseButton
    }

    fun updateQuestion(k: Boolean?) {

        if (k == true) {
            quizViewModel.moveToNext()
            textView.setText(quizViewModel.questionText)

        } else if (k == false) {
            quizViewModel.moveToLast()
            textView.setText(quizViewModel.questionText)
        }
        if (quizViewModel.currentQuestion.flag == 1) {
            //改变做过题按钮的颜色 flag 1 0
            var ch: Choose?
            ch = quizViewModel.chooseList.get(quizViewModel.currentNum)

            //做过
            if (ch != null) {
                if (ch.c == true) {
                    updateColor(ch.result, trueButton, falseButton)
                } else {
                    updateColor(ch.result, falseButton, trueButton)
                }
            }
        }

        for (i in quizViewModel.questionBank) {
            if (i.flag == 1)
                continue
            else
                return
        }
        Toast.makeText(this, "您的分数是" + quizViewModel.score, Toast.LENGTH_LONG).show()
    }

    fun updateColor(t: Boolean, chooseButton: Button, noChooseButton: Button) {
        quizViewModel.currentQuestion.flag = 1
        if (t == true) {
//                    Log.d(TAG,chooseButton.solidColor.toString())
            chooseButton.background.setColorFilter(
                getColor(R.color.teal_200),
                PorterDuff.Mode.SRC_ATOP
            )
        } else {
            noChooseButton.background.setColorFilter(
                getColor(R.color.teal_200),
                PorterDuff.Mode.SRC_ATOP
            )
            chooseButton.background.setColorFilter(
                getColor(R.color.error),
                PorterDuff.Mode.SRC_ATOP
            )

        }
    }

    private fun showCustomToast(message: String) {
        // 获取 LayoutInflater 服务
        val inflater = layoutInflater
        // 使用自定义布局 inflate 视图
        val layout = inflater.inflate(
            R.layout.mine_toast,
            findViewById(R.id.main_layout),
            true
        )

        // 设置 TextView 文本
        val text = layout.findViewById<TextView>(R.id.toast_text)
        text.text = message

        // 设置 ImageView 图片（如果需要）
//        val image = layout.findViewById<ImageView>(R.id.image)
//        image.setImageResource(R.drawable.ic_info_black_24dp)

        // 创建并显示 Toast
        val toast = Toast(applicationContext).apply {
            duration = Toast.LENGTH_LONG
            view = layout
            setGravity(Gravity.TOP or Gravity.CENTER, 0, 500)
        }
        toast.show()
    }


    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onstart()")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPaues()")

    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume()")

    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy()")

    }

    override fun onRestart() {
        super.onRestart()
        Log.d(TAG, "onRestart")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop")
    }

    override fun onSaveInstanceState(savedInstanceState: Bundle) {
        super.onSaveInstanceState(savedInstanceState)
        Log.i(TAG, "onSaveInstanceState1111111111111111")
        savedInstanceState.putInt(KEY_INDEX, quizViewModel.currentNum)
    }

}

